package com.achobeta.recruitment.controller.interact;

import com.achobeta.recruitment.common.AppResult;
import com.achobeta.recruitment.common.ResultCode;
import com.achobeta.recruitment.common.Rule;
import com.achobeta.recruitment.model.Attachment;
import com.achobeta.recruitment.model.Manager;
import com.achobeta.recruitment.model.WxUser;
import com.achobeta.recruitment.service.interact.AttachmentService;
import com.achobeta.recruitment.utils.CheckUtils;
import com.achobeta.recruitment.utils.LimitUtils;
import com.achobeta.recruitment.utils.MediaUtils;
import com.achobeta.recruitment.utils.SessionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-30
 * Time: 21:35
 */

@Api(tags = "附件信息相关")
@Slf4j
@RestController
@RequestMapping("/attachment")
public class AttachmentController {

    @Value("${redirect.domain}")
    private String redirectDomain;

    @Value("${redirect.fe}")
    private String redirectFE;

    @Value("${test.guy}")
    private String guy;

    @Autowired
    private AttachmentService attachmentService;

    @ApiOperation(value = "上传附件", notes = "返回的data为附件保存的路径，String")
    @PostMapping("/submit")
    public AppResult<String> attachment(HttpServletRequest request,
                                        @ApiParam("附件") @NonNull @RequestPart("attachment") MultipartFile file) throws IOException {
        CheckUtils.checkNULL(file);
        // 获取一个路径
        String path = MediaUtils.getImageUniquePath(file.getOriginalFilename());
        CheckUtils.checkNULL(path);
        // 插入附件表
        WxUser wxUser = SessionUtils.getWxUser(request);
        String openid = wxUser.getOpenid();
//        String openid = guy;

        System.out.println(path);
        // 下载文件（如果已提交，这里是下载不了的）
        attachmentService.loadFile(file, path, openid);
        // 构造附件对象
        Attachment attachment = new Attachment();
        String origin = file.getOriginalFilename();
        attachment.setRemark(origin.substring(0, Math.min(origin.length(), 100)));
        attachment.setOpenid(openid);
//        path = "http://" + redirectDomain + "/" + path;//改为全路径
        attachment.setAttachment(path);
        Date date = new Date();
        attachment.setCreateTime(date);
        attachment.setUpdateTime(date);
        attachment.setDeleteState((byte) 0);
        // 调用service层
        attachmentService.insertAttachment(attachment);
        // 返回成功（路径）
        return AppResult.success("上传成功", path);
    }


    @ApiOperation(value = "删除附件", notes = "无data")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public AppResult delete(HttpServletRequest request,
                            @ApiParam("附件id") @NonNull @RequestParam("id") Integer id) {
        // 获取当前登录用户信息
        WxUser wxUser = SessionUtils.getWxUser(request);
        String openid = wxUser.getOpenid();
//        String openid = guy;
        // 创建删除对象
        Attachment attachment = new Attachment();
        attachment.setOpenid(openid);
        attachment.setId(id);
        // 删除
        attachmentService.deleteAttachment(attachment);
        // 返回成功
        return AppResult.success();
    }

    @ApiOperation(value = "获取附件列表", notes = "data为附件列表(Attachment对象集合)")
    @GetMapping("/list")
    public AppResult<List<Attachment>> getAttachment(HttpServletRequest request) {
        // 获取当前登录用户信息
        WxUser wxUser = SessionUtils.getWxUser(request);
        String openid = wxUser.getOpenid();
//        String openid = guy;
        // 查询附件表
        List<Attachment> attachments = attachmentService.selectByOpenId(openid);
        attachments = attachments == null ? new ArrayList<>() : attachments;
        // 成功返回
        return AppResult.success(attachments);
    }
    @RequestMapping(value = "/manager/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "通过openid获取一个用户的附件列表", notes = "data为附件列表(Attachment对象集合)")
    public AppResult<List<Attachment>> getAttachmentByOpenid(HttpServletRequest request,
                                                             @NonNull @ApiParam("openid") @RequestParam("openid") String openid) {
        // 获取当前登录的管理员
        Manager manager = SessionUtils.getManager(request);
        // 判断是否有权限
        if(!LimitUtils.hasPower(manager, Rule.ATTACHMENT_LIST_RULE)) {
            log.warn(ResultCode.FAILED_MANAGER_NOT_POWERS.toString());
            return AppResult.failed(ResultCode.FAILED_MANAGER_NOT_POWERS);
        }
        // 查询附件表
        List<Attachment> attachments = attachmentService.selectByOpenId(openid);
        attachments = attachments == null ? new ArrayList<>() : attachments;
        // 成功返回
        return AppResult.success(attachments);
    }
}
